package com.lhm.dao;

import com.lhm.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.regex.Pattern;

@Repository
public class BookDao {
    @Autowired
    MongoTemplate mongoTemplate;



    //添加
    public void addBoke(Book book){
        mongoTemplate.save(book);
    }

    //删除
    public void delById(String id){
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.findAndRemove(query,Book.class);
    }

    //全查询
    public List<Book> findAll(){
        List<Book> books = mongoTemplate.findAll(Book.class);
        return books;
    }
    //根据id查询
    public List<Book> findByUid(String uid){
        Query query = new Query(Criteria.where("uid").is(uid));
        List<Book> books = mongoTemplate.find(query, Book.class);
        return books;
    }

    //分页查询
    public List<Book> findByPage(int start,int num){
        Query query = new Query();
        query.skip(start).limit(num);
        List<Book> books = mongoTemplate.find(query, Book.class);
        return books;
    }

    //根据类型id查询
    public List<Book> findByTypeid(String typeid){
        Query query = new Query(Criteria.where("typeid").is(typeid));
        List<Book> books = mongoTemplate.find(query, Book.class);
        return books;
    }

    //模糊查询
    public List<Book> findBy(String title){
        Criteria c = new Criteria();
        Pattern pattern = Pattern.compile("^.*"+title+".*$",Pattern.CASE_INSENSITIVE);
        c.and("title").regex(pattern);
        Query query = new Query(c);
        List<Book> books = mongoTemplate.find(query,Book.class);
        return books;
    }
}
